# encoding=utf-8

import sys, os
if hasattr(sys, 'frozen'):
    os.environ['PATH'] = sys._MEIPASS + ";" + os.environ['PATH']

import PyQt5.QtWidgets as qw
import PyQt5.QtCore as qc
from PyQt5 import QtGui
import ui_main
from PyQt5.QtCore import QTimer, Qt, pyqtSignal
import sys,time
import numpy as np
import random
import json

import logging
from serial import Serial
import threading
from time import sleep
from configparser import ConfigParser
from serial.serialutil import *
import serial.tools.list_ports
import pyqtgraph as pg

import ui_home
import ui_set

class widgetSet(qw.QWidget, ui_set.Ui_Form):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

class myWindow(qw.QMainWindow, ui_home.Ui_MainWindow):
    signal_recv_data = pyqtSignal(str)
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        # init gui
        self.statusbar.showMessage("status:ok")
        self.pw = pg.PlotWidget()
        self.verticalLayout.addWidget(self.pw )

        self.w_set = widgetSet()

        self.settings = qc.QSettings("config.ini", qc.QSettings.IniFormat)
        self.mode = int(self.settings.value("SETUP/MODE"))

        # 绑定信号与槽

        # definition
        self.uart_start = 0

        def check_valid_net():
            ports_value = []
            ports_list = serial.tools.list_ports.comports()
            for i in range(len(ports_list)):
                ports_value.append(ports_list[i][0])
            # print("ports_value is ", ports_value)

            if (0 == len(ports_value)):
                print("can't find uart port.")
                self.comboBox_uart.clear()
                self.comboBox_uart.setCurrentIndex(-1)
            else:
                for i in range(len(ports_value)):
                    index = self.comboBox_uart.findText(ports_value[i], Qt.MatchFixedString)
                    if (index < 0):
                        self.comboBox_uart.addItem(ports_value[i])
                    # else:
                    #     print("curent port is ", self.comboBox_uart.currentText())

        # 开启监听线程
        def gui_status_thread():
            print("start gui_status_thread.")
            while(True):
                check_valid_uart()
                sleep(3)

        # threading.Thread(target=gui_status_thread, daemon=True).start()
    def menu_user_cb(self):
        print("Click menu user...........")

if __name__ == "__main__":
    app = qw.QApplication(sys.argv)
    w = myWindow()
    w.show()

    sys.exit(app.exec_())
